var formidable = require("formidable")
var path = require("path")
var fs = require("fs")
var User = require('./wxuser')

module.exports=function (req, res, next) {

        var form = new formidable.IncomingForm()
        form.parse(req, function (err, fields, files) {
            if (err) {
                console.log(err)
                return next(err)
            }
            var basename = path.basename(files.avatar.path)
            var extname = path.extname(files.avatar.name)

            fs.rename(files.avatar.path, path.join(__dirname, '../public/img', basename + extname), function (err) {
                if (err) {
                    console.log(err)
                    return next(err)
                }
                var last_modified_time = Date.now()


                User.findOneAndUpdate({ _id: fields._id }, { avatar: 'public/img/' + basename + extname ,last_modified_time:last_modified_time}, { new: true }, function (err, user) {
                    if (err) {
                        console.log(err)
                        return next(err)
                    }

                    res.status(200).json({
                        code: 0,
                        msg: '修改成功',
                        user,
                    })
                })
            })

        });
    }
